package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.feign.EmailFeignClient;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.AuthCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

/**
 * Created by Heweipo on 2021/2/15.
 */
@Service
@Slf4j
public class AuthCodeServiceImpl implements AuthCodeService{

    @Autowired
    private AuthCodeDao authCodeDao;
    @Autowired
    private EmailFeignClient emailFeignClient;

    @Override
    public AuthCode create(AuthCode authCode) {

        // 生成随机码
        String code = RandomUtils.nextInt(999999) +"";
        while (code.length() < 6){
            code = code + RandomUtils.nextInt(9);
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        authCode.setCode(code);
        authCode.setCreatetime(simpleDateFormat.format(new Date()));
        authCode.setExpiretime(simpleDateFormat.format(new Date(System.currentTimeMillis()+5*60*1000)));
        log.info("生成验证码：{}",authCode);


        // 请求邮件服务发送
        boolean sendRs = emailFeignClient.sendSmsByEmail(authCode.getEmail(),authCode.getCode());
        if(sendRs){
            // 插入数据库
            AuthCode rs = authCodeDao.save(authCode);
            return rs;
        }

        return null;
    }

    /**
     * 校验验证码是否正确，0正确 1错误 2超时
     * @param email
     * @param code
     * @return 0正确 1错误 2超时
     */
    @Override
    public Integer validate(String email, String code) {

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Optional<AuthCode> one = authCodeDao.findOne(Example.of(authCode));
        if(one.isPresent()){
            AuthCode rs = one.get();
            try {
                Date expireTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(rs.getExpiretime());
                if(expireTime.getTime() > System.currentTimeMillis()){
                    return 0;
                }else {
                    return 2;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        return 1;
    }
}
